package com.zzjson.concurrency.example.singleton;

import com.zzjson.concurrency.annoations.ThreadSafe;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 懒汉模式 -》 双重同步锁单例模式
 * 单例实例在第一次使用时进行创建
 */
@ThreadSafe
public class SingletonExample5 {
	private int i;


	// 私有构造函数
	private SingletonExample5() {
		i = i++;
	}

	// 1、memory = allocate() 分配对象的内存空间
	// 2、ctorInstance() 初始化对象
	// 3、instance = memory 设置instance指向刚分配的内存

	// 单例对象 volatile + 双重检测机制 -> 禁止指令重排
	private volatile static SingletonExample5 instance = null;

	// 静态的工厂方法
	public static SingletonExample5 getInstance() {
		if (instance == null) { // 双重检测机制        // B
			synchronized (SingletonExample5.class) { // 同步锁
			if (instance == null) {
				instance = new SingletonExample5(); // A - 3
			}
			}
		}
		return instance;
	}

	public static void main(String[] args) {
		ExecutorService executorService = Executors.newFixedThreadPool(2);
		for (int i = 0; i < 1000; i++) {

			executorService.execute(() -> {
				SingletonExample5 instance = SingletonExample5.getInstance();
			});
		}
	}
}
